package wsi.db;

import org.rygh.core.db.access.CoreDao;
import org.rygh.core.security.USecurity;

public class WebCache {

	public static void cache(String key, String content) {
		cache(key, content, false);
	}

	public static void cache(String key, String content, boolean force) {
		if (!force)
			if (content == null || content.trim().isEmpty())
				return;

		delete(key);

		WebCacheModel t = new WebCacheModel();
		t.setName(key);
		t.setHashCode(getHashCode(key));
		t.setContent(content);

		CoreDao.insert(t);
	}

	public static void delete(String key) {
		int code = getHashCode(key);

		CoreDao.delete(WebCacheModel.class, " tmain." + WebCacheModel.HASH_CODE
				+ " = " + code);
	}

	public static String fetch(String key) {
		int code = getHashCode(key);

		WebCacheModel t = CoreDao.selectByInt(WebCacheModel.class, code,
				WebCacheModel.HASH_CODE);

		return t == null ? null : t.getContent();
	}

	public static int getHashCode(String key) {
		return USecurity.md5(key).hashCode();
	}
}
